<template>
  <view class="type-selector-container" v-if="visible">
    <view class="type-selector-mask" @tap="closeSelector"></view>
    <view class="type-selector-content">
      <view class="type-selector-header">
        <uni-icons class="type-selector-close" type="close" size="22" color="#999" @tap="closeSelector" />
        <text class="type-selector-title">{{ title }}</text>
        <uni-icons class="type-selector-manage" type="gear" size="22" color="#666" @tap="goToManage" />
      </view>
      
      <!-- 🎯 搜索框（当类型较多时显示） -->
      <view v-if="typeList.length > 8" class="search-box">
        <uni-icons type="search" size="16" color="#999" />
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          placeholder="搜索类型..."
          @input="onSearchInput"
          @focus="onSearchFocus"
          @blur="onSearchBlur"
        />
        <view v-if="searchKeyword" class="clear-search" @tap="clearSearch">
          <uni-icons type="clear" size="14" color="#ccc" />
        </view>
      </view>
      <scroll-view 
        class="type-selector-body"
        scroll-y
        :show-scrollbar="false"
        :enhanced="true"
      >
        <!-- 🎯 类型网格容器 -->
        <view class="type-grid">
          <view
            class="type-item"
            v-for="(type, index) in filteredTypeList"
            :key="index"
            @tap="selectType(type)"
          >
            <view class="type-content">
              <image class="type-icon" :src="type.icon" mode="aspectFit"></image>
              <text class="type-name">{{ type.name }}</text>
            </view>
          </view>
        </view>
        
        <!-- 🎯 如果类型很多，显示数量提示 -->
        <view v-if="typeList.length > 8" class="type-count-tip">
          <text>{{ searchKeyword ? `找到 ${filteredTypeList.length} 种类型` : `共 ${typeList.length} 种类型` }}</text>
        </view>
        
        <!-- 🎯 无搜索结果提示 -->
        <view v-if="searchKeyword && filteredTypeList.length === 0" class="no-result-tip">
          <text>未找到"{{ searchKeyword }}"相关的类型</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import CommApi from '@/sheep/api/comm/comm';

const props = defineProps({
  businType: { type: String, required: true },
  title: { type: String, default: '类型' },
  visible: { type: Boolean, default: false }
});

const emit = defineEmits(['update:visible', 'type-selected']);

const typeList = ref([]);
const searchKeyword = ref('');

// 🎯 过滤后的类型列表 - 本地搜索按名称匹配
const filteredTypeList = computed(() => {
  if (!searchKeyword.value.trim()) {
    return typeList.value;
  }
  
  const keyword = searchKeyword.value.trim().toLowerCase();
  return typeList.value.filter(type => {
    // 按名称搜索，支持模糊匹配
    return type.name && type.name.toLowerCase().includes(keyword);
  });
});

const getTypeList = async () => {
  try {
    uni.showLoading({ title: '加载中...' });
  const res = await CommApi.queryUserBusinCategory({ businType: props.businType });
    uni.hideLoading();
  if (res.code === 0 && res.data) {
      typeList.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        icon: item.iconUrl || '/static/icons/event-types/other.png'
      }));
  } else {
      uni.showToast({ title: '获取类型失败', icon: 'none' });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
  }
};

const selectType = (type) => {
  console.log('选择类型:', type);
  emit('type-selected', type);
  closeSelector();
};

const closeSelector = () => {
  emit('update:visible', false);
};

const goToManage = () => {
  uni.navigateTo({
    url: `/pages/comm/type-manage?businType=${props.businType}&pageTitle=${props.title}`
  });
};

// 🎯 搜索相关方法
const onSearchInput = (e) => {
  // 实时本地搜索，无需防抖因为是本地过滤
  searchKeyword.value = e.detail.value;
};

const onSearchFocus = () => {
  console.log('搜索框获得焦点');
};

const onSearchBlur = () => {
  console.log('搜索框失去焦点');
};

const clearSearch = () => {
  searchKeyword.value = '';
  uni.showToast({ 
    title: '已清除搜索', 
    icon: 'none',
    duration: 1000
  });
};

onMounted(getTypeList);
watch(() => props.businType, getTypeList);
</script>

<style lang="scss" scoped>
.type-selector-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.type-selector-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.type-selector-content {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 20rpx 30rpx 30rpx 30rpx;
  max-height: 70vh; /* 🎯 适当增加高度以适应4列布局 */
  display: flex;
  flex-direction: column;
}

.type-selector-header {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  height: 48rpx;
  flex-shrink: 0; /* 🎯 防止头部被压缩 */
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20rpx;
  padding: 0 16rpx;
  margin-bottom: 16rpx;
  height: 60rpx;
  flex-shrink: 0;
  border: 1px solid #e8e8e8;
  
  &:focus-within {
    border-color: #007AFF;
    background-color: #f8f9ff;
  }
}

.search-input {
  flex: 1;
  margin-left: 8rpx;
  font-size: 24rpx;
  color: #333;
  height: 100%;
}

.clear-search {
  padding: 6rpx;
  margin-left: 8rpx;
  border-radius: 50%;
  transition: background-color 0.2s;
  
  &:active {
    background-color: #e0e0e0;
  }
}

.type-selector-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin: 0 auto;
  display: block;
  text-align: center;
}

.type-selector-manage {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
}

.type-selector-close {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
}

.type-selector-body {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20rpx;
}

.type-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 0 10rpx;
}

.type-item {
  width: 25%;
  padding: 10rpx;
  box-sizing: border-box;
  position: relative;
  
  &:active {
    transform: scale(0.98);
  }
}

.type-content {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  border: 1px solid transparent;
  min-height: 120rpx;
  
  &:active {
    background-color: #e9ecef;
  }
}

.type-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-bottom: 10rpx;
  flex-shrink: 0;
}

.type-name {
  font-size: 28rpx;
  color: #333;
  text-align: center;
  line-height: 1.2;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}

.type-count-tip {
  text-align: center;
  padding: 20rpx;
  margin-top: 10rpx;
  
  text {
    font-size: 22rpx;
    color: #999;
    background-color: #f0f0f0;
    padding: 8rpx 16rpx;
    border-radius: 16rpx;
  }
}

.no-result-tip {
  text-align: center;
  padding: 40rpx 20rpx;
  
  text {
    font-size: 26rpx;
    color: #999;
  }
}
</style> 